<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function swirl(matrix) {
            var row = matrix.length
            var column = matrix[0].length
            var loopr = Math.floor(row / 2)
            var loopc = Math.floor(column / 2)
            var loop = Math.floor((Math.min(row, column) + 1) / 2)
            if (row == 1) return matrix[0]
            if (column == 1) return matrix.map(row => row[0])
            var i = 0, j = 0, endi = row-1,endj=column-1
            // console.log(loopc, loopr, loop)
            var result = []
            while (loop > 0) {
                for (j; j < endj; j++) {
                    result.push(matrix[i][j])
                }
                for (i; i < endi; i++) {
                    result.push(matrix[i][j])
                }
                for (j; j >= column-endj; j--) {
                    result.push(matrix[i][j])
                }
                for (i; i >= row-endi; i--) {
                    result.push(matrix[i][j])
                }
                loop--
                i++
                j++ 
                endi--
                endj--
            }

            if (row == column && row % 2 == 1) {
                result.push(matrix[loopr][loopc])
            }
            return result
        }

        function spiralMatrix(matrix) {
            var m = matrix.length
            var n = matrix[0].length
            var result = []
            let num = 1;
            let rowStart = 0, rowEnd = m - 1;
            let colStart = 0, colEnd = n - 1;
            while (num <= m * n) {
                // 从左到右
                for (let i = colStart; i <= colEnd; i++) {
                    result.push(matrix[rowStart][i])
                    num++
                }
                rowStart++;

                // 从上到下
                for (let i = rowStart; i <= rowEnd; i++) {
                    result.push(matrix[i][colEnd])
                    num++
                }
                colEnd--;

                // 从右到左
                for (let i = colEnd; i >= colStart; i--) {
                    result.push(matrix[rowEnd][i])
                    num++
                }
                rowEnd--;

                // 从下到上
                for (let i = rowEnd; i >= rowStart; i--) {
                    result.push(matrix[i][colStart])
                    num++
                }
                colStart++;
            }

            return result
        }

        console.log(swirl([[2, 3, 4], [5, 6, 7], [8, 9, 10], [11, 12, 13], [14, 15, 16]]))
        // 2  3  4
        // 5  6  7
        // 8  9  10
        // 11 12 13
        // 14 15 16

        // 17  18 19
        // 21 22 23 
    </script>
</body>

</html>